package priv.pfz.basedao.mybatis.sqlprovider;

import org.apache.ibatis.builder.annotation.ProviderContext;
import priv.pfz.basedao.info.DaoInfo;
import priv.pfz.basedao.mybatis.DaoInfoCache;
import priv.pfz.basedao.sharding.ShardingInfo;
import priv.pfz.basedao.sharding.ShardingManager;
import priv.pfz.basedao.sqlbuilder.SQL;

/**
 * DELETE FROM table WHERE id=#{id}
 * logic delete: UPDATE table SET delete_flag = id WHERE id=#{id} AND delete_flag=0
 * @author yyjxp
 * 2024/1/28 23:55
 */
public class DeleteByIdSqlProvider extends BaseSqlProvider {

    public String provideSql(ProviderContext context) {
        return provideShardingSql(null, context);
    }

    public String provideShardingSql(ShardingInfo shardingInfo, ProviderContext context) {
        DaoInfo daoInfo = DaoInfoCache.getDaoInfo(context.getMapperType());
        ShardingManager shardingManager = new ShardingManager(daoInfo, shardingInfo);

        SQL sql = new SQL();
        if (daoInfo.isEnableLogicDelete()) {
            sql.UPDATE(shardingManager.getShardingTable());
            sql.SET(getLogicDeleteSet(daoInfo));
            sql.WHERE(getIdEqualsArg("arg0"));
            sql.WHERE(getLogicDeleteWhere(daoInfo));
        } else {
            sql.DELETE_FROM(shardingManager.getShardingTable());
            sql.WHERE(getIdEqualsArg("arg0"));
        }
        String sqlStr = sql.toString();
        sqlStr += shardingManager.getThirdShardingStr();
        System.out.println(sqlStr);
        return sqlStr;
    }
}
